/**
 * 
 */
package com.xjy.common.util;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

/**
 * 键表
 *
 */
public class KeyTable {
	
	private long id;
	private long nextAvailable;
	private long cacheSize;
	private String tablename;
	public String getTablename() {
		return tablename;
	}
	public void setTablename(String tablename) {
		this.tablename = tablename;
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public long getNextAvailable() {
		return nextAvailable;
	}
	public void setNextAvailable(long nextAvailable) {
		this.nextAvailable = nextAvailable;
	}
	public long getCacheSize() {
		return cacheSize;
	}
	public void setCacheSize(long cacheSize) {
		this.cacheSize = cacheSize;
	}
	
	
	private static long next = -1;
	private static long last = -1;
	
	public static long getNextKey(String tablename) {
		return doGetNextKey(tablename);
	}
	
	private static synchronized long doGetNextKey(String tablename) {
		if(next == -1)
			refresh(tablename);
		long result = next;
		next++;
		if(next > last)
			refresh(tablename);
		return result;
	}
	
	private static void refresh(String tablename) {
		SessionFactory sessionFactory = (SessionFactory)SpringBeanProxy.getBean("sessionFactory");
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String hql=" from KeyTable";
			Object objResult=null;
			if(tablename!=null && !tablename.trim().equals("")){
				hql+=" where tablename='"+tablename+"'";
			}
			objResult = session.createQuery(hql).uniqueResult();
			if(objResult == null)
				objResult=session.createQuery(" from KeyTable").uniqueResult();
			KeyTable keyTable = (KeyTable)objResult;
			next = keyTable.getNextAvailable();
			last = next + keyTable.getCacheSize() - 1;
			keyTable.setNextAvailable(last + 1);
			session.flush();
		}
		finally {
			if(session != null)
				session.close();
		}
	}
}
